package server

import (
	"chatServer/src/msgConst"
	"chatServer/src/util"
	"net"
	"strconv"
	"strings"
	"time"
)

type User struct {
	userName  string
	Conn      net.Conn
	RoomID    int
	LoginTime int64
}

//createUser 创建用户
func createUser(conn net.Conn) {
	user := &User{userName: conn.RemoteAddr().String(), Conn: conn, LoginTime: time.Now().Unix()}
	ChatServer.addUser(user)
	user.loginHandle()
	user.readMsg()
}

// 登录提示
func (u *User) loginHandle() {
	tips := ">>>>>>>>>>>>>>>>>>>欢迎登录，当前的聊天房间有\n"
	for _, chatRoom := range ChatServer.roomMap {
		tips += "房间名:" + chatRoom.roomName + ",房间号:" + strconv.Itoa(chatRoom.roomID) + "\n"
	}
	tips += "请使用" + msgConst.ChooseRoom + "#房间号 来切换需要进入的房间\n"
	tips += "也可以使用" + msgConst.Rename + "#昵称 来进行你用户名的修改\n"
	u.send2Client(tips)
}

// 监听客户端
func (u *User) readMsg() {
	buf := make([]byte, 4096)
	for {
		readN, err := u.Conn.Read(buf)
		if readN == 0 {
			return
		}
		if err != nil {
			util.HandleErr(err)
			return
		}
		msg := string(buf[:readN-1])
		u.doMsg(msg)
	}
}

// 消息处理
func (u *User) doMsg(msg string) {
	msgArgs := strings.Split(msg, "#")
	if len(msgArgs) > 1 {
		switch msgArgs[0] {
		case msgConst.ChooseRoom:
			u.chooseRoom(msgArgs[1])
			break
		case msgConst.Rename:
			u.rename(msgArgs[1])
			break
		default:
			u.send2Client(msgConst.IllegalArgs)
		}
	} else {
		u.sendChat(msg)
	}
}

// 选择房间
func (u *User) chooseRoom(roomIDStr string) {
	roomID, err := strconv.Atoi(roomIDStr)
	if err != nil {
		util.HandleErr(err)
		u.send2Client(msgConst.IllegalArgs)
		return
	}
	if u.RoomID == roomID {
		u.send2Client(msgConst.IllegalChoose)
		return
	}
	chatRoom := ChatServer.roomMap[roomID]
	if chatRoom == nil {
		u.send2Client(msgConst.IllegalRoomID)
		return
	}
	if u.RoomID != 0 { // 退出原来的房间
		oldRoom := ChatServer.roomMap[u.RoomID]
		oldRoom.deleteUser(u)
	}
	u.RoomID = roomID
	chatRoom.addUserChannel <- u
}

// 修改昵称
func (u *User) rename(newName string) {
	if ChatServer.userMap[newName] != nil {
		u.send2Client(msgConst.IllegalSameName)
		return
	}
	oldName := u.userName
	u.userName = util.FilterStr(newName)
	ChatServer.userRename(oldName, u)
	if u.RoomID != 0 { // 修改房间内的昵称
		chatRoom := ChatServer.roomMap[u.RoomID]
		chatRoom.userRename(oldName, u)
	}
	u.send2Client("[系统]:修改昵称成功，你现在的昵称是[" + newName + "]")
}

// 发送聊天信息
func (u *User) sendChat(msg string) {
	chatRoom := ChatServer.roomMap[u.RoomID]
	if chatRoom == nil {
		u.send2Client(msgConst.IllegalUnChooseRoom)
		return
	}
	msg = "[" + u.userName + "]:" + util.FilterStr(msg)
	chatRoom.chatChannel <- msg
}

// 发送消息给客户端
func (u *User) send2Client(msg string) {
	_, err := u.Conn.Write([]byte(msg + "\n"))
	if err != nil {
		util.HandleErr(err)
	}
}
